package com.nowcoder.community.service;

import com.nowcoder.community.dao.LoginTicketMapper;
import com.nowcoder.community.dao.UserMapper;
import com.nowcoder.community.entity.LoginTicket;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.MailClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.*;

@Service
public class UserService implements CommunityConstant {

    @Autowired
    private LoginTicketMapper loginTicketMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

    /*注入配置信息:域名*/
    @Value("${community.path.domain}")
    private String domain;

    /*注入配置信息:项目路径*/
    @Value("${server.servlet.context-path}")
    private String contextPath;


    /**
     * 通过用户id查询用户
     */
    public User findUserById(int id) {
        return userMapper.selectById(id);
    }

    /**
     * 注册用户
     */
    //可能返回各种信息，用Map集合封装
    public Map<String, Object> register(User user) {
        Map<String, Object> map = new HashMap<>();

        //异常处理：是否为空
        if (user == null) {
            throw new IllegalArgumentException("参数不能为空！");
        }
        if (StringUtils.isBlank(user.getUsername())) {
            map.put("usernameMesg", "账号不能为空！");
            return map;
        }
        if (StringUtils.isBlank(user.getPassword())) {
            map.put("passwordMesg", "密码不能为空！");
            return map;
        }
        if (StringUtils.isBlank(user.getEmail())) {
            map.put("emailMesg", "邮箱不能为空！");
            return map;
        }

        //验证账号
        User user1 = userMapper.selectByName(user.getUsername());
        if (user1 != null) {
            map.put("usernameMsg", "该账号已存在！");
            return map;
        }
        //验证邮箱
        user1 = userMapper.selectByEmail(user.getEmail());
        if (user1 != null) {
            map.put("emailMsg", "该邮箱已被注册！");
            return map;
        }

        //注册用户：向用户表中添加数据
        //数据处理
        //产生密码盐
        user.setSalt(CommunityUtil.generateUUID().substring(0,5));
        //密码加密
        user.setPassword(CommunityUtil.md5(user.getPassword()+user.getSalt()));
        //数据填充
        //设置为普通用户
        user.setType(0);
        //设置用户状态为未激活
        user.setStatus(0);
        //设置激活码
        user.setActivationCode(CommunityUtil.generateUUID());
        //设置用户头像
            //字符串中拼接变量
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/&dt.png",new Random().nextInt(1000)));
        //设置创建时间
        user.setCreateTime(new Date());
        //向用户表中添加处理好的数据对象
        userMapper.insertUser(user);

        // 发送html激活邮件
        //访问模版，需要传一个参数，构造参数
        Context context = new Context();
        //把传入模版的变量传入这个对象
        //邮箱
        context.setVariable("email",user.getEmail());
        //激活地址:如http://localhost:8080/community/activation/101/code
        String url = domain+contextPath+"/activation"+ '/'+user.getId()+'/'+user.getActivationCode();
        context.setVariable("url",url);

        //调用模版引擎生成html：传入模版文件路径和内容
        String content = templateEngine.process("/mail/activation",context);

        //使用邮件发送给浏览器，浏览器自动渲染
        mailClient.sendMail(user.getEmail(),"激活账号",content);

        return map;

    }

    /**
     * 激活账号
     */

    public int activation(int userId,String code){
        //通过id查找用户
        User user = userMapper.selectById(userId);
        //根据用户状态做不同的处理
        if(user.getStatus()==1){
            //重复激活
            return ACTIVATION_REPEAT;
        }else  if(code.equals(user.getActivationCode())){
            //激活码一样可以激活
            userMapper.updateStatus(userId,1);
            return ACTIVATION_SUCCESS;
        }else {
           //激活码不一样，激活失败
            return ACTIVATION_FAILURE;
        }

    }

    /**
     * 登陆业务处理
     */
    //可能有多种返回结果，使用map集合封装
    public Map<String,Object> login(String username,String password,int expiredSecond){
        //结果变量
        Map<String,Object> map = new HashMap<>();

        //异常处理：空值
        if(StringUtils.isBlank(username)){
            map.put("usernameMsg","用户名不能为空");
            return map;
        }
        if(StringUtils.isBlank(password)){
            map.put("passwordMsg","用户名不能为空");
            return map;
        }

        //验证账号
        User user = userMapper.selectByName(username);
        if(user == null){
            map.put("usernameMsg","该账号不存在");
            return map;
        }

        //验证状态
        if(user.getStatus()==0){
            map.put("usernameMsg","该账号未激活");
            return map;
        }

        //验证密码
        //先将明文密码拼接盐加密，再比较
       password = CommunityUtil.md5(password + user.getSalt());
        if(!password.equals(user.getPassword())){
            map.put("passwordMsg","密码不正确");
            return map;
        }

        //登陆成功，生成登录凭证(用表实现，作用与session类似)
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setStatus(0);
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setExpired(new Date(System.currentTimeMillis()+ expiredSecond*1000));
        loginTicketMapper.insertLoginTicket(loginTicket);

        map.put("ticket",loginTicket.getTicket());
        return  map;
    }

    /**
     * 登出
     * @param ticket
     */
    public void logout(String ticket){
        loginTicketMapper.updateStatus(ticket,1);
    }

    /**
     * 通过ticket查询凭证对象
     */
    public LoginTicket findLoginTicket(String ticket){
        LoginTicket loginTicket = loginTicketMapper.selectByTicket(ticket);
        return loginTicket;
    }

    /**
     * 更改用户头像地址
     */
    public int updateHeader(int userId, String headerUrl){
       return userMapper.updateHeader(userId,headerUrl);
    }

    /**
     * 通过用户名查询用户
     */
    public User findUserByName(String username){
        return userMapper.selectByName(username);
    }
}
